const express = require('express');
const co = require('co');
const logger = require('flogger').getLogger();
const config = require('config');
const IMMessage = require('../mongo/im-message');
const Session = require('../util/session');
const APIResult = require('../util/util').APIResult;
const Utility = require('../util/util').Utility;
var rongCloud = require('rongcloud-sdk');
var router = express.Router();
rongCloud.init(config.RONGCLOUD_APP_KEY, config.RONGCLOUD_APP_SECRET);

/**
 * @api {get} /webim/message/history 查询聊天记录
 * @apiName GetUser
 * @apiGroup IMMessage
 * @apiVersion 0.1.0
 *
 * @apiParam {String} target 指定目标用户
 * @apiParam {Number} before 在该时间戳之前的聊天记录
 *
 * @apiSuccess {Object[]} messages 返回和指定用户在指定时间之前的聊天记录
 *
 * @apiExample {bash} 示例：
 *      GET /webim/message/history?target=K69DpFSlN
 *
 * @apiSuccessExample 成功响应:
 *    HTTP/1.1 200 OK
 *     {
 *       "code": 200,
 *       "result": [
 *         {
 *           "_id": "57df3ee7c352877011c7e916",
 *           "channelType": "PERSON",
 *           "fromUserId": "K69DpFSlN",
 *           "toUserId": "ZXEkcNQOm",
 *           "msgTimestamp": 1474248423003,
 *           "timestamp": 1474248423003,
 *           "objectName": "RC:TxtMsg",
 *           "content": {
 *             "content": "发嘎嘎\n",
 *             "extra": "普通消息"
 *           },
 *           "msgUID": "5BK0-3DMB-C79R-5EV0",
 *           "encodedFromUserId": "K69DpFSlN",
 *           "encodedToUserId": "ZXEkcNQOm",
 *           "__v": 0
 *         },
 *         {
 *           "_id": "57de09cbc352877011c7e913",
 *           "channelType": "PERSON",
 *           "fromUserId": "K69DpFSlN",
 *           "toUserId": "ZXEkcNQOm",
 *           "msgTimestamp": 1474169291724,
 *           "timestamp": 1474169291724,
 *           "objectName": "RC:TxtMsg",
 *           "content": {
 *             "content": "发\n",
 *             "extra": "普通消息"
 *           }
 *         },
 *         ...
 *       ]
 *     }
 */
router.get('/history', function (req, res, next) {
  let sentTime = parseInt(req.query.before) || 9999999999999;
  let target = req.query.target;
  let userId = Session.getCurrentUserId(req);
  let targetId = Utility.stringToNumber(target);
  logger.info(`用户 ${userId} 正在查询和 ${targetId} 的历史消息`);
  co(function*() {
    let messages = yield IMMessage.find({
      $or: [
        {
          fromUserId: userId,
          toUserId: targetId
        },
        {
          toUserId: userId,
          fromUserId: targetId
        }
      ],
      timestamp: {
        $lt: sentTime
      }
    }).sort({'timestamp': 'desc'}).limit(20);
    messages = messages.map(message => {
      let msg = message.toObject();
      msg.fromUserId = Utility.numberToString(+msg.fromUserId);
      msg.toUserId = Utility.numberToString(+msg.toUserId);
      return msg;
    });
    res.send(new APIResult(200, messages));
  }).catch(next);
});

module.exports = router;
